/*
 * @Description: 布局使用
 */
import createHandles from '@/handles/handle-list/create';
import { useBaseInfoStore } from '@/store/modules/base-info';
import { useTemplateStore } from '@/store/modules/template';
import { useSuperviseSetStore } from '@/store/modules/summary/supervise-set';
import { useSummaryCommentStore } from '@/store/modules/summary/comment';

import { mapState, mapActions, mapWritableState } from 'pinia';

import { initParams } from '@/handles/handle-list/summary/modules/sign/helper';
import globalData from '@/plugins/data';
import globalMethods from '@/plugins/methods';
import { useSummaryTabStore } from '@/store/modules/summary/tab';
import { initWaterMark } from '@/plugins/directives/modules/watermark';
import api from '@/api';
import emitter from "@/utils/emitter";

export default {
  data() {
    return {
      ckEditorCover: false,
    }
  },
  computed: {
    ...mapState(useTemplateStore, ['isIframeReady']),
    ...mapWritableState(useSummaryTabStore, ['activeIndex', 'isLoadWorkflow']),
    ...mapState(useBaseInfoStore, [
      'baseInfo',
      'isBaseInfoReady',
      'isHideGlobalLoading',
      'isEdit',
      'isDataReady'
    ]),
    //页面准备好
    pageReady() {
      //数据获取完、iframe加载完
      return (
        this.isDataReady && this.isBaseInfoReady && this.isIframeReady && this.isHideGlobalLoading
      );
    },
    //是否展示右侧面板
    isShowRightPanel() {
      if (!this.baseInfo) return false;
      const {
        hasRelationDataPanel, //是否有相关数据面板
        hasWorkflowPredictionPanel, //是否有流程预测面板
        hasPeoplesPanel, //是否有常用联系人面板
        hasRecentlyTemplatePanel, //是否有常用模板面板
        hasWorkflowBookPanel //是否有流程说明书
      } = this.baseInfo.businessData.other;
      return (
        hasRelationDataPanel ||
        hasWorkflowPredictionPanel ||
        hasPeoplesPanel ||
        hasRecentlyTemplatePanel ||
        hasWorkflowBookPanel
      );
    }
  },
  methods: {
    ...mapActions(useBaseInfoStore, ['getBaseInfo', 'setPreviewImgRef', 'setDataReady','updatePushPeopleList']),
    ...mapActions(useSuperviseSetStore, ['setSuperviseData']),
    ...mapActions(useSummaryCommentStore, ['initData']),
    ...mapActions(useSummaryTabStore, ['changeActiveIndex']),
    /**
     * @description: 检查有没有需要弹提示的
     * @param {Object}baseInfo
     * @return {*}
     */
    checkTip(baseInfo) {
      const {
        businessData: { superviseData }
      } = baseInfo;
      const { warn4Supervise } = superviseData;
      //模板设置了部门主管为督办人员，但该部门没有指定主管！
      if (warn4Supervise) {
        return this.$warning({ content: warn4Supervise });
      }
    },
    async getData(baseInfo) {
      const {
        zwIframe: {
          mainbody: {
            moduleId, moduleType,
          },
        },
        businessData: {
          affair: {
            id,
            objectId
          },
        },
      } = baseInfo;
      let showPostscript = this.baseInfo?.businessData?.summary?.canAddComment!==false;
      if (showPostscript){
        const result = await api.commentGetList({
          moduleId,
          moduleType,
          affairId: id,
          queryType: 2,
        });
        //没有意见锚点，且有附言时候默认选中附言
        if (!globalData.contentAnchor && result.commentData[0].commentTotal > 0) {
          this.state.siderActiveTab = "tab1";
        } else {
          this.state.siderActiveTab = "tab2";
        }
        this.$nextTick(async () => {//发起附言
          await emitter.publish('init-postScript-data', result);
        })
      }else {
        this.state.siderActiveTab = "tab2";
      }
      //意见
      this.updatePushPeopleList(await api.commentGetAtList(objectId));
    },
  },
  async created() {
    try {
      //请求水印数据
      initWaterMark();
      //获取baseInfo
      let baseInfo = await this.getBaseInfo();
      if(globalData.isSummary) {
        this.getData(baseInfo);
      }
      //处理页面先设置一些全局参数在window上 设置页面的<title>信息
      document.title =
        baseInfo.businessData.summary.showTitle ||
        globalMethods.i18n('collaboration.newcoll.htmltitle');
      //多页签模式 -设置页签标题
      const topWindow = window.getCtpTop();
      if (topWindow['isMultipleTabs'] && topWindow['setWindowTabTitle']) {
        let attribute = frameElement.getAttribute("id");
        topWindow.setWindowTabTitle(document.title, attribute, true);
      }
      if (globalData.isSummary) {
        initParams(baseInfo);
        //设置督办数据
        this.setSuperviseData(baseInfo.businessData.superviseData, true);
        //初始化其他数据。跟踪设置和其他草稿数据
        this.initData(baseInfo.businessData);
      } else {
        //检查一下有没有需要弹提示的。新建页面用
        this.checkTip(baseInfo);
      }
      //全局通知baseinfo接口准备就绪
      this.$root.$emit('dataReady');
      const inSpecialState = [15, 16, 17];
      let { workflow, currentUser, formData, affair, other } = baseInfo.businessData;
      workflowModule.initWorkflowParams({
        fn: () => {
          let baseInfoStore = useBaseInfoStore();
          baseInfoStore.weekSubmit = true;
          createHandles.send();
        },
        tWindow: window,
        processId: workflow.processId,
        workitemId: workflow.itemId,
        wfTraceType: workflow.wfTraceType,
        appName: affair.appEnumStr || other.moduleTypeName,
        processXml: workflow.xml,
        caseId: workflow.caseId,
        currentActivityId: workflow.activityId,
        currentWorkitemId: workflow.itemId,
        currentUserId: currentUser.id,
        currentAccountId: currentUser.loginAccount,
        formData: formData,
        mastrid: workflow.mastrid,
        debugMode: workflow.debugMode,
        processTemplateId: workflow.processTemplateId,
        currentWorkItemIsInSpecial: affair.subState && inSpecialState.includes(affair.subState),
        matchRequestToken: workflow.matchRequestToken,
        useNowexpirationTime: workflow.useNowexpirationTime,
        NPS: workflow.NPS,
        canBugReport: globalData.isSummary ? 'true' : 'false',
        newGenerateNodeId: workflow.newGenerateNodeId,
        secretLevel: workflow.secretLevel,
        isValidate: 'true',
        postInfo: workflow.postInfo // 需要协同传递过来
      });
      //适配致码
      window.scanCodeInputValue = other.templateScanCodeInput ? '1' : '0';
      //自由协同预制流程图信息场景 新建页面
      if (!globalData.isSummary) {
        window?.workflowModule?.initProcessXml();
      }
    } finally {
      this.setDataReady();
      this.setPreviewImgRef(this.$refs.previewImg);
      emitter.subscribe('ckEditor-onCover', (cover) => this.ckEditorCover = !!cover);
    }
  }
};
